//
//  HRSRequestNetWorking.m
//  HRSNetWorking
//
//  Created by huangrensheng on 16/4/18.
//  Copyright © 2016年 laber. All rights reserved.
//

#import "HRSRequestNetWorking.h"

@interface HRSRequestNetWorking()<NSURLSessionDelegate,MBProgressHUDDelegate>
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation HRSRequestNetWorking

#pragma GET
/**
 *  get请求方式
 *
 *  @param url      请求的地址
 *  @param params   参数
 *  @param callBack 回掉函数
 */
- (void)getWithUrl:(NSString *)url params:(NSDictionary *)params success:(successResponse)success error:(errorResponse)errors{
    url= [[self getFormartUrlWithParams:params url:url] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *reUrl = [NSURL URLWithString:url];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:reUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task =[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves  error:nil];
            if (dict[@"msg"]) {
                [[[[[UIApplication sharedApplication] delegate] window] rootViewController].view makeToast:dict[@"msg"]];
            }
            if ([dict[@"code"] integerValue]==1) {// 1:success  0:error
                success(dict);
            }else{
                errors(error);
            }
        });
//        callBack(data,response,error);
    }];
    [task resume];
}

/**
 *  get请求 地址拼接   get请求参数直接拼接在地址后面
 *
 *  @param params  请求的参数
 *  @param baseUrl 请求的地址
 *
 *  @return 返回拼接好的地址
 */
- (NSString *)getFormartUrlWithParams:(NSDictionary *)params url:(NSString *)baseUrl{
    NSMutableString *url = [NSMutableString stringWithString:baseUrl];
    for (int i = 0; i<params.count ; i++){
        NSString *key = [params allKeys][i];
        if (i == 0) {
            [url appendFormat:@"?%@=%@",key,params[key]];
        }else{
            if ([params[key] isEqualToString:@""]) {
                continue;
            }
            [url appendFormat:@"&%@=%@",key,params[key]];
        }
    }
    [url appendFormat:@"&%@=%@",@"token",[[NSUserDefaults standardUserDefaults] stringForKey:@"token"]];
    return url;
}

#pragma POST
/**
 *  post 请求地址
 *
 *  @param url      请求的地址
 *  @param params   请求的参数
 *  @param callBack 回调函数
 */
- (void)postWithUrl:(NSString *)url params:(NSDictionary *)params success:(successResponse)success error:(errorResponse)errors{
    [self showHudImage:@"加载中..."];
    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"POST";
    request.timeoutInterval = 60;//超时时间
    request.HTTPBody = [[self postFormartUrlWithParams:params] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task =[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hidHud];
            NSString *errorString=[error description];
//            NSLog(@"network error=%@ code=%ld  response=%@",errorString,error.code,response);
            if (errorString) {
                [self showTextOnly:@"请求服务器错误"];
                return ;
            }
            NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves  error:nil];
            if (dict[@"msg"] && ![dict[@"msg"] isKindOfClass:[NSNull class]]) {
                [self showTextOnly:dict[@"msg"]];
            }
            if ([dict[@"code"] integerValue]==1) {// 1:success  0:error
                success(dict[@"data"]);
            }else{
                errors(error);
            }
        });
//        callBack(data,response,error);
    }];
    [task resume];
}

/**
 *  拼接post 的请求体
 *  @param params 参数
 *  @return 反悔拼接好的请求体
 */
- (NSString *)postFormartUrlWithParams:(NSDictionary *)params{
     NSMutableString *body = [NSMutableString stringWithString:@""];
    for (int i = 0; i<params.count ; i++){
        NSString *key = [params allKeys][i];
        if (i == 0) {
            [body appendFormat:@"%@=%@",key,params[key]];
        }else{
            if ([params[key] isEqualToString:@""]) {
                continue;
            }
            [body appendFormat:@"&%@=%@",key,params[key]];
        }
    }
    [body appendFormat:@"&%@=%@",@"token",[[NSUserDefaults standardUserDefaults] stringForKey:@"token"]];
    return body;
}

/**
 *  显示加载视图
 *
 *  @param message 加载时显示的信息
 */
- (void)showHudImage:(NSString *)message{
    self.hud = [[MBProgressHUD alloc] initWithWindow:[[AppDelegate shareInstance] window]];
    self.hud.delegate = self;
    //小矩形的背景色
    self.hud.color = DARK_GRAY_COLOR;//这儿表示无背景
    //显示的文字
    self.hud.labelText = message;
    [[[AppDelegate shareInstance] window] addSubview:self.hud];
    [self.hud show:YES];
}
/**
 *  只显示文字提示信息
 *
 *  @param text 显示的信息
 */
- (void)showTextOnly:(NSString *)text{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[AppDelegate shareInstance] window] animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabelText = text;
    hud.detailsLabelFont = [UIFont systemFontOfSize:15];
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:2];

}
/**
 *  隐藏加载框
 */
- (void)hidHud{
    [self.hud hide:YES];
}
//隐藏加载视图后的代理
- (void)hudWasHidden:(MBProgressHUD *)hud{
    [self.hud removeFromSuperview];
    self.hud = nil;
}

#pragma mark 
//防止重复回调 只在错误时回调
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error{
    if (error) {
        NSString *errorString=[error description];
        NSLog(@"network error=%@ code=%ld",errorString,error.code);
        if (error.code==-1001) {
            errorString=@"请求超时";
            [self showTextOnly:errorString];
        }
    }
}
@end
